package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private IVoucherOrderService iVoucherOrderService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 线程池 - 放一个线程
     */
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    /**
     * 初始化 - 向线程池中提交订单处理线程
     */
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";

        @Override
        public void run() {
            while (true) {
                try {
                    // 获取Redis Stream消息队列中的消息
                    // XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );

                    if (list == null || list.isEmpty()) {
                        // 如果获取失败，说明没有消息，继续下一次循环
                        continue;
                    }

                    // 解析消息中的订单信息
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    // 完成下单操作
                    // 扣减库存
                    // CAS锁 + 库存>0(解决成功率低问题)
                    seckillVoucherService.update(Wrappers.<SeckillVoucher>lambdaUpdate()
                            .setSql("stock = stock - 1")
                            .eq(SeckillVoucher::getVoucherId, voucherOrder.getVoucherId())
                            .gt(SeckillVoucher::getStock, 0));
                    // 创建订单
                    save(voucherOrder);

                    /* ACK确认 */
                    // SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", entries.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }

        /**
         * 失败后尝试一次PendingList中的未确认队列
         */
        private void handlePendingList() {
            try {
                // 获取Redis Stream PendingList消息
                // XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders 0
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                        StreamOffset.create(queueName, ReadOffset.from("0"))
                );

                if (list == null || list.isEmpty()) {
                    // 如果获取失败，说明没有PendingList没有未Ack的消息，继续下一次循环
                    return;
                }

                // 解析消息中的订单信息
                MapRecord<String, Object, Object> entries = list.get(0);
                Map<Object, Object> value = entries.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                // 完成下单操作
                // 扣减库存
                // CAS锁 + 库存>0(解决成功率低问题)
                seckillVoucherService.update(Wrappers.<SeckillVoucher>lambdaUpdate()
                        .setSql("stock = stock - 1")
                        .eq(SeckillVoucher::getVoucherId, voucherOrder.getVoucherId())
                        .gt(SeckillVoucher::getStock, 0));
                // 创建订单
                save(voucherOrder);

                /* ACK确认 */
                // SACK stream.orders g1 id
                stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", entries.getId());
            } catch (Exception e) {
                log.error("处理PendingList订单异常", e);
                handlePendingList();
            }
        }
    }


    /**
     * HOT lua脚本
     */
    public static final DefaultRedisScript<Long> HOT_SECKILL_SCRIPT;

    static {
        HOT_SECKILL_SCRIPT = new DefaultRedisScript<>();
        HOT_SECKILL_SCRIPT.setLocation(new ClassPathResource("lua/seckill.lua"));
        HOT_SECKILL_SCRIPT.setResultType(Long.class);
    }

    /**
     * 秒杀优惠卷业务
     *
     * @param voucherId 优惠卷ID
     * @return 同一响应结果
     */
    @Override
    public Result sekkillVoucher(Long voucherId) {
        /* 执行HOT lua脚本 */
        Long userId = UserHolder.getUser().getId();
        // 设置分布式全局唯一订单ID，RedisID自增
        long orderId = redisIdWorker.nextId(INCR_SHOP_ID);
        Long result = stringRedisTemplate.execute(HOT_SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId));
        assert result != null;
        int r = result.intValue();
        // 失败情况
        if (r != 0) {
            return Result.fail(r == 1 ? "no count" : "repeat");
        }
        return Result.ok(orderId);
    }


    /*  @Override
      public Result sekkillVoucher(Long voucherId) {
          *//* 优惠卷基本信息校验 *//*
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        // 验证卷ID是否存在
        if (voucher == null) {
            return Result.fail("优惠卷不存在!");
        }
        // 使用日期校验
        LocalDateTime now = LocalDateTime.now();
        if (voucher.getBeginTime().isAfter(now) || voucher.getEndTime().isBefore(now)) {
            return Result.fail("优惠卷不在有效使用日期内!");
        }
        // 库存校验
        if (voucher.getStock() < 1) {
            return Result.fail("no count");
        }

        Long userId = UserHolder.getUser().getId();

        *//* 一人一单分布式锁 *//*
        // 创建锁对象(一人一单，锁用户)
        // Redisson可重入锁
        RLock lock = redissonClient.getLock(LOCK_ORDER_KEY + userId);
        // 获取锁
        boolean isLock = lock.tryLock();
        if (!isLock) {
            // 获取锁失败，返回失败或重试
            return Result.fail("不允许重复下单!");
        }
        try {
            // 自调用事务会失效，需要获取当前类的Spring代理对象
            return iVoucherOrderService.createVoucherOrder(voucherId);
        } finally {
            // 释放锁
            lock.unlock();
        }
    }
    */


    /**
     * 订单操作
     * 这里使用悲观锁：synchronized
     * 但是不建议加在方法上，方法上表示this范围，即每次请求都串行执行
     * 应该加锁在用户ID上，为每个用户进行加锁操作
     * ----
     * 用户ID加悲观锁
     * Long.toString()底层是new String()，导致统一ID锁不同
     * intern()能从字符串常量池中拿数据，保证同ID的锁唯一
     * ----
     * 事务 + 同步锁，存在锁处理完，事务还未结束的情况
     * 依然会导致多线程数据问题（隔离级别RR问题）
     * 要提升synchronized的范围，保证先提交事务，再释放锁
     *
     * @param voucherId 优惠卷ID
     * @return 订单
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Result createVoucherOrder(Long voucherId) {
        /* 一人一单订单查询 */
        Long userId = UserHolder.getUser().getId();
        Integer count = lambdaQuery()
                .eq(VoucherOrder::getUserId, userId)
                .eq(VoucherOrder::getVoucherId, voucherId)
                .count();
        if (count > 0) {
            return Result.fail("one person only allow one order!");
        }

        /* 扣减库存 */
        // CAS锁 + 库存>0(解决成功率低问题)
        boolean updateFlag = seckillVoucherService.update(Wrappers.<SeckillVoucher>lambdaUpdate()
                .setSql("stock = stock - 1")
                .eq(SeckillVoucher::getVoucherId, voucherId)
                .gt(SeckillVoucher::getStock, 0));
        if (!updateFlag) {
            // 扣减库存失败
            return Result.fail("reduce order fail，on count!");
        }

        /* 创建订单 */
        VoucherOrder voucherOrder = new VoucherOrder();
        // 设置分布式全局唯一订单ID，RedisID自增
        long orderId = redisIdWorker.nextId(INCR_SHOP_ID);
        voucherOrder.setId(orderId);
        // 设置用户ID
        voucherOrder.setUserId(userId);
        // 设置优惠卷ID
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        return Result.ok(orderId);
    }
}
